#!/usr/bin/env python3
# coding:utf-8

import asyncio
import aiomqtt

Config = {
    "ip": "192.168.111.17",
    "port": 1883,
    "username": "test",
    "password": "test",
    "ca_file": "",
}


class MqttClient:
    def __init__(self, config):
        self.config = config
        self.mqttc = None

    async def loop_run(self):
        ip = self.config["ip"]
        port = self.config["port"]
        username = self.config["username"]
        password = self.config["password"]
        try:
            async with aiomqtt.Client(ip, port, username=username, password=password, timeout=10) as client:
                self.mqttc = client
                await client.subscribe("test/test")
                async for msg in client.messages:
                    print("recv: ", msg.topic, msg.payload)
        except aiomqtt.MqttError as e:
            print(f"MQTT error: {e}")
        except asyncio.CancelledError:
            print("Operation was cancelled")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")

    async def publish_test(self):
        await asyncio.sleep(6)
        count = 0
        while True:
            if self.mqttc:
                await self.mqttc.publish("test/aaa", f"this is mqtt test {count}")
                count += 1
            await asyncio.sleep(1)


async def main():
    mqttc = MqttClient(Config)
    await asyncio.gather(
        mqttc.loop_run(),
        mqttc.publish_test(),
    )


if __name__ == "__main__":
    asyncio.run(main())
